<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/3/26
 * Time: 上午11:06
 */

namespace console\controllers;

use common\models\Coupon;
use common\models\Timer;
use yii\console\Controller;
use yii;
use yii\mongodb\Database;

class CouponTimerController extends Controller
{
    /**
     * 定时任务
     */
    public function actionExecute()
    {
        $time = time();
        $space = strtotime(date("Y-m-d") . " 00:00:00");
        $tempTime = $time - $space;
        $timerList = Timer::find()->asArray()->all();
        if (count($timerList) > 0) {
            foreach ($timerList as $timer) {
                $spaceTime = (abs($tempTime - $timer['execute_at']));
                if ($spaceTime < 5 * 60 && ($time - $timer['latest_at']) > 2 * $spaceTime) {
                    $model = Timer::findOne($timer['id']);
                    if ($model == null) {
                        continue;
                    }
                    $coupon = Coupon::findOne($model->coupon_id);
                    if (($coupon->origin_num - $coupon->use_num) <= $timer['min_num']) {
                        if ($coupon->origin_num + $timer['num'] >= 1100) {
                            $timer['num'] = 1100 - $coupon->origin_num;
                        }
                        $describe = date('Y-m-d H:i:s', $time) . "新增" . $timer['num'] . '张';
                        $model->describe = $describe;
                        $model->latest_at = $time;
                        $coupon->origin_num = $coupon->origin_num + $timer['num'];
                        $coupon->save();
                        $model->save();
                    }
                }
            }
        }
    }
}
